﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.Windows;
using System.Windows.Threading;
using Edgar.Frontend.Wpf.ViewModels;

namespace Edgar.Frontend.Wpf.CharacterSheet
{
    public class CharacterSheetPaginator : DocumentPaginator
    {
        private Thickness DefaultMargin = new Thickness(75);

        private Size _PageSize;
        private Thickness _Margin;

        private CharacterViewModel _CharacterViewModel;

        public CharacterSheetPaginator(CharacterViewModel characterViewModel, Size pageSize)
        {
            _PageSize = pageSize;
            _Margin = DefaultMargin;
            _CharacterViewModel = characterViewModel;
        }

        public override DocumentPage GetPage(int pageNumber)
        {
            var page = new CharacterSheetFirstPage()
            {
                Height = PageSizeNoMargin.Height,
                Width = PageSizeNoMargin.Width,
                DataContext = _CharacterViewModel
            };

            DoEvents();
            page.Margin = _Margin;
            page.Measure(PageSizeNoMargin);
            page.Arrange(new Rect(new Point(0, 0), PageSize));

            return new DocumentPage(page);
        }


        private void DoEvents()
        {
            var frame = new DispatcherFrame();
            Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrame), frame);
            Dispatcher.PushFrame(frame);
        }


        private object ExitFrame(object f)
        {
            ((DispatcherFrame)f).Continue = false;
            return null;
        }

        public override bool IsPageCountValid
        {
            get { return true; }
        }

        public override int PageCount
        {
            get { return 1; }
        }

        public override Size PageSize
        {
            get
            {
                return _PageSize;
            }
            set
            {
                _PageSize = value;
            }
        }

        public Size PageSizeNoMargin
        {
            get { return new Size(PageSize.Width - _Margin.Left - _Margin.Right, PageSize.Height - _Margin.Top - _Margin.Bottom); }
        }

        public override IDocumentPaginatorSource Source
        {
            get { return null; }
        }
    }
}
